﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Slam.Configuration;
using System.Text.RegularExpressions;
using Slam;
using Microsoft.SharePoint;
using System.Web;
using System.Data.EntityClient;
using TagQueries = SlamCms.SharePoint.Tagging.Data.Queries;
using SlamCms.SharePoint.Data;
using Slam.SharePoint;

namespace SlamCms.SharePoint.Tagging.Services
{
	public class TaggingServices
	{
		private string _connectionString;
		private string _dataSchema;
		private DataMapping _currentDataMapping;
		
		private static bool _userTableExists = false;

		protected string ConnectionString
		{
			get
			{
				return _connectionString;
			}
		}

		protected DataMapping CurrentDataMapping
		{
			get
			{
				return _currentDataMapping;
			}
		}

		protected string DataSchema
		{
			get
			{
				return _dataSchema;
			}
		}

		protected string ModelName
		{
			get
			{
				return "Data.SlamCms";
			}
		}

		protected string TagsEntitySetName
		{
			get
			{
				return "Tags";
			}
		}

		public TaggingServices()
		{
			IConfigurationManager slamConfiguration = ComponentService.GetInstance<IConfigurationManager>();
			_currentDataMapping = slamConfiguration.DataMapping;
			string siteCollection = SPContext.GetContext(HttpContext.Current).Site.ServerRelativeUrl.TrimStart('/');
			if (!String.IsNullOrEmpty(siteCollection) && slamConfiguration.DataMappings.ContainsKey(siteCollection))
			{
				_currentDataMapping = slamConfiguration.DataMappings[siteCollection];
			}
			if (slamConfiguration is XmlConfigurationManager)
			{
				_dataSchema = ((XmlSqlDataMapping)_currentDataMapping).GetDataSchema();
				_connectionString = ((XmlSqlDataMapping)_currentDataMapping).GetConnectionString();
			}

			if (String.IsNullOrEmpty(_connectionString))
			{
				_connectionString = slamConfiguration.GetSection<ConnectionStringSection>("ConnectionStrings").Default;
			}
			else
			{
				_connectionString = slamConfiguration.GetSection<ConnectionStringSection>("ConnectionStrings").GetConnectionString(_connectionString);
			}

			EntityConnectionStringBuilder entityConnection = new EntityConnectionStringBuilder();
			entityConnection.Provider = "System.Data.SqlClient";
			if (!_connectionString.Contains("Persist Security Info"))
			{
				_connectionString = _connectionString.TrimEnd(';') + ";Persist Security Info=True;";
			}
			entityConnection.ProviderConnectionString = _connectionString;
			entityConnection.Metadata = String.Format("res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", ModelName);

			_connectionString = entityConnection.ToString();

			EnsureTaggingTablesExist();
		}

		private void EnsureTaggingTablesExist()
		{
			Entities context = new Entities(_connectionString);

			if (!_userTableExists)
			{
				_userTableExists = context.ExecuteStoreQuery<int>(String.Format(TagQueries.VerifyTableExists, _dataSchema, "User")).FirstOrDefault() > 0;
			}

			if (!_userTableExists)
			{
				context.ExecuteStoreCommand(String.Format(TagQueries.CreateUserTable, _dataSchema + "."));
				_userTableExists = true;
			}
		}

		public string GetScopeForListItem(SPListItem listItem)
		{
			ConfiguredType type = listItem.GetSlamConfiguredType();
			string contentTypeName = CurrentDataMapping.GetTypeAttribute(type.Id, type.Name, "ContentItemType");
			if (String.IsNullOrEmpty(contentTypeName))
			{
				contentTypeName = type.Name;
			}
			return contentTypeName;
		}
	}
}
